package com.tianji.aigc.memory;

import com.tianji.aigc.utils.MessageUtil;
import com.tianji.common.utils.CollUtils;
import org.springframework.ai.chat.memory.ChatMemory;
import org.springframework.ai.chat.messages.Message;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;

import java.util.List;

public class RedisChatMemory implements ChatMemory {

    //默认redis中的前缀
    public static final String DEFAULT_PREFIX = "CHAT:";

    private final String prefix;

    public RedisChatMemory() {
        this.prefix = DEFAULT_PREFIX;
    }

    public RedisChatMemory(String prefix) {
        this.prefix = prefix;
    }

    @Autowired
    private StringRedisTemplate redisTemplate;

    /**
     * 将消息添加到指定会话的redis列表中
     * @param conversationId 会话id
     * @param messages 消息
     */
    @Override
    public void add(String conversationId, List<Message> messages) {
        if (CollUtils.isEmpty(messages)){
            //如果消息列表为空,则直接返回
            return;
        }
       var redisKey = this.getKey(conversationId);
       var listOps = this.redisTemplate.boundListOps(redisKey);
       //将消息序列化并且添加到Redis中
        messages.forEach(msg -> listOps.rightPush(MessageUtil.toJson(msg)));
    }

    @Override
    public List<Message> get(String conversationId) {
        return List.of();
    }

    /**
     * 清理指定会话的redis列表
     * @param conversationId 会话id
     */

    @Override
    public void clear(String conversationId) {
        var key = this.getKey(conversationId);
        this.redisTemplate.delete(key);
    }

    private String getKey(String conversationId) {
        return prefix + conversationId;
    }
}
